package com.linck.im.client;

import com.linck.im.client.context.ChannelContext;
import com.linck.im.client.context.StageContext;
import com.linck.im.client.controller.LoginController;
import com.linck.im.client.initial.ChatClientInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class ImClient extends Application {

    private static final Logger log = LoggerFactory.getLogger(ImClient.class);

    private String host = "127.0.0.1";

    private int port = 8083;

    Bootstrap bootstrap;

    EventLoopGroup group;

    @Override
    public void start(Stage stage) throws IOException {
        StageContext.setStage(stage);
        FXMLLoader fxmlLoader = new FXMLLoader(ImClient.class.getResource("controller/login-view.fxml"));
        Scene scene = new Scene(fxmlLoader.load(), 480, 360);
        stage.setTitle("IM Client");
        stage.setScene(scene);

        // 发起网络连接
        group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChatClientInitializer());
        try {
            Channel channel = bootstrap.connect(host, port).sync().channel();
            ChannelContext.setChannel(channel);
            ChannelContext.NET_STATE = 1;
            log.info("网络连接成功");
        } catch (Exception e) {
            log.info("网络连接失败", e);
        }
        LoginController.drawNetworkInfo();
        stage.show();
    }

    @Override
    public void stop() throws Exception {
        group.shutdownGracefully().sync();
        System.exit(0);
    }

    public static void main(String[] args) {
        launch();
    }
}